package com.icoolkj.mall.inventory.service.impl;

import com.icoolkj.mall.common.Result;
import com.icoolkj.mall.common.exception.BusinessException;
import com.icoolkj.mall.inventory.dto.InventoryResponse;
import com.icoolkj.mall.inventory.mapper.InventoryMapper;
import com.icoolkj.mall.inventory.service.InventoryService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/01/16 13:48
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    private Logger logger = LoggerFactory.getLogger(InventoryServiceImpl.class);

    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    @Transactional
    public void reduceInventory(Long productId, Integer inventoryQuantity) {

        logger.info("扣减库存服务调用...");
        logger.info("[reduceBalance] currenet XID: {}", RootContext.getXID());

        Integer inventory = inventoryMapper.getInventory(productId);
        if(inventory == null  || inventory < inventoryQuantity){
            throw new BusinessException("no enough inventory.");
        }
        int updateInventory = inventoryMapper.reduceInventory(productId, inventoryQuantity, new Date());
        if(updateInventory ==0) {
            throw new BusinessException("deduce inventory failed.");
        }
    }

    @Override
    public Result<?> getInventoryQuantity(Long productId) {
        Integer inventory = inventoryMapper.getInventory(productId);
        if(inventory == null){
            return Result.fail("productId wrong, please check product id.");
        }
        InventoryResponse inventoryResponse = new InventoryResponse();
        inventoryResponse.setProductId(productId);
        inventoryResponse.setInventoryQuantity(inventory);
        return Result.ok(inventory);
    }
}
